import Card from '@/components/Card';
import type { ProColumns } from '@/components/Pro';
import {
  ModalForm,
  ProForm,
  ProFormInstance,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  ProTable,
  QueryFilter,
} from '@/components/Pro';
import {
  cabinetComponentControllerGetCabinetPkgList as TableList,
  cabinetComponentControllerUploadPkg as Uploadfile,
} from '@/services/ess/cabinetComponent';
import { emsComponentControllerUpdatePkg as UpdatePkg } from '@/services/ess/emsComponent';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import { UploadOutlined } from '@ant-design/icons';
// import { useModel } from '@@/exports';
import { Button, message, Space, Upload } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
// import Access from '@/components/Access';
import { useIntl } from 'umi';

const UpgradeManagement: React.FC = () => {
  // const { initialState } = useModel('@@initialState');
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  const [readonly, setReadonly] = useState(false);
  const [currentRow, setCurrentRow] = useState({});
  const modalFormRef = useRef<ProFormInstance>();
  const formRef = useRef<ProFormInstance>();
  const [deviceOptions, setDeviceOptions] = useState([]);
  const [deviceStaions, setdeviceStaions] = useState([]);
  const [packageName, setPackageName] = useState<string>('');
  const [versionFile, setFile] = useState<File>();
  const [ProTableData, setProTableData] = useState<any>([]);
  const intl = useIntl();
  const tableColumns: ProColumns[] = [
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.generalProcedure.SN' }),
      dataIndex: 'pageIndex',
      valueType: 'index',
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.componentManagement.componentType' }),
      dataIndex: 'componentCode',
      key: 'componentCode',
      render: (_, record) => {
        return (
          <span>
            {
              deviceOptions?.filter((item) => {
                return item.value === record?.componentCode;
              })[0]?.label
            }
          </span>
        );
      },
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.componentManagement.componentName' }),
      dataIndex: 'fileName',
      hideInSearch: true,
      render: (_, record) => {
        return (
          <span>
            {
              deviceOptions?.filter((item) => {
                return item.value === record?.componentCode;
              })[0]?.remark
            }
          </span>
        );
      },
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.componentManagement.versionNumber' }),
      dataIndex: 'version',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({
        id: 'remoteUpgradeMangment.componentManagement.upgradePackageStoragePath',
      }),
      dataIndex: 'filePath',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'remoteUpgradeMangment.componentManagement.uploadTime' }),
      dataIndex: 'updatedTime',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.tenantManagementMenu.status' }),
      dataIndex: 'status',
      hideInSearch: true,
      render: (_, record) => {
        return (
          <span>
            {
              deviceStaions?.filter((item) => {
                return String(item.value) === String(record?.status);
              })[0]?.label
            }
          </span>
        );
      },
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.tenantManagementMenu.remarks' }),
      dataIndex: 'remark',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.tenantManagementMenu.operation' }),
      dataIndex: 'operation',
      hideInSearch: true,
      render: (_, record) => (
        <Space>
          <a
            key="edit"
            onClick={() => {
              setReadonly(false);
              handleModalOpen(true);
              setCurrentRow({
                ...record,
              });
            }}
          >
            {intl.formatMessage({ id: 'systemManagement.generalProcedure.edit' })}
          </a>
        </Space>
      ),
    },
  ];

  useEffect(() => {
    fetchDictInfo(DATABASE_TYPE_ENUM.ESS_CABINET_TYPE).then((res) => {
      setDeviceOptions(res);
    });

    fetchDictInfo(DATABASE_TYPE_ENUM.ENABLE_DEVI).then((res) => {
      setdeviceStaions(res);
    });

    TableList({
      current: '1',
      pageSize: '20',
    }).then((res) => {
      if (res.success) {
        setProTableData(res.data.records);
      }
    });
  }, []);
  return (
    <>
      <QueryFilter
        split
        formRef={formRef}
        submitter={{
          searchConfig: {
            submitText: intl.formatMessage({
              id: 'remoteUpgradeMangment.componentManagement.upload',
            }),
          },
        }}
        onFinish={async (values) => {
          try {
            let reslut = await Uploadfile(
              {
                componentCode: values.componentCode,
                version: values.version,
                otaName: packageName,
              },
              versionFile,
            );
            if (reslut.success) {
              TableList({
                current: '1',
                pageSize: '20',
                componentCode: values.componentCode,
              }).then((res) => {
                console.log('查询分页', res);
                if (res.success) {
                  setProTableData(res.data.records);
                }
              });
              message.success(
                intl.formatMessage({
                  id: 'remoteUpgradeMangment.generalProcedure.submitSuccess',
                }),
              );
            }
          } catch (error) {
            console.log(error);
          }
        }}
        onReset={() => {
          TableList({
            current: '1',
            pageSize: '20',
          }).then((res) => {
            if (res.success) {
              setProTableData(res.data.records);
            }
          });
          formRef?.current?.submit();
        }}
      >
        <ProFormSelect
          request={() => fetchDictInfo(DATABASE_TYPE_ENUM.ESS_CABINET_TYPE)}
          name="componentCode"
          label={intl.formatMessage({
            id: 'remoteUpgradeMangment.componentManagement.componentType',
          })}
        />
        <ProFormText
          name="version"
          label={intl.formatMessage({
            id: 'remoteUpgradeMangment.componentManagement.versionNumber',
          })}
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'remoteUpgradeMangment.requiredFields.versionNumber',
              }),
            },
            {
              pattern: /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/, // 正则表达式校验版本号格式，例如：1.0.0
              message: intl.formatMessage({
                id: 'remoteUpgradeMangment.requiredFields.incorrectFormat',
              }),
            },
          ]}
        />

        <ProForm.Item
          label={intl.formatMessage({ id: 'remoteUpgradeMangment.componentManagement.otaFile' })}
          name="file"
          rules={[
            {
              required: true,
              message: intl.formatMessage({
                id: 'remoteUpgradeMangment.requiredFields.selectFile',
              }),
            },
          ]}
        >
          <Upload
            maxCount={1}
            accept=".zip, .rar"
            beforeUpload={(file) => {
              setPackageName(file.name);
              console.log(packageName);
              setFile(file);
            }}
            customRequest={(req) => {
              const { onSuccess, onError } = req;
              const { file } = req;
              if (file.size / 1024 / 1024 > 500) {
                message.error(
                  intl.formatMessage({
                    id: 'systemManagement.neddTochange.fileMax500m',
                  }),
                );
                onError('文件大小超过500M，请重新上传');
                return false;
              } else {
                console.log('我这边文件上传成功');
                onSuccess({ result_status: true });
              }
            }}
          >
            <Button icon={<UploadOutlined />} style={{ width: '200px' }}></Button>
          </Upload>
        </ProForm.Item>
      </QueryFilter>

      <Card
        title={intl.formatMessage({
          id: 'remoteUpgradeMangment.componentManagement.uploadHistory',
        })}
        className="global-remote-card"
        bordered={false}
      >
        <ProTable
          search={false}
          rowKey={'pageIndex'}
          columns={tableColumns}
          dataSource={ProTableData}
        ></ProTable>
        <ModalForm
          formRef={modalFormRef}
          modalProps={{
            destroyOnClose: true,
          }}
          initialValues={{
            ...currentRow,
            status:
              currentRow?.status || currentRow?.status === 0 ? Boolean(currentRow?.status) : '',
          }}
          submitter={{
            render: (_, doms) => !readonly && <Space>{doms}</Space>,
          }}
          title={intl.formatMessage({
            id: 'remoteUpgradeMangment.componentManagement.changeVersionStatus',
          })}
          layout="horizontal"
          width={650}
          colProps={{ xs: 12 }}
          labelCol={{
            flex: `0 0 110px`,
          }}
          open={createModalOpen}
          onOpenChange={handleModalOpen}
          onFinish={async (value) => {
            let params = {
              ...value,
              pkgId: currentRow?.id,
            };
            let reslut = await UpdatePkg(params);
            if (reslut.success) {
              handleModalOpen(false);
              TableList({
                current: '1',
                pageSize: '20',
              }).then((res) => {
                if (res.success) {
                  setProTableData(res.data.records);
                }
              });
            }
            console.log(reslut);
          }}
        >
          <ProFormRadio.Group
            label={intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.status' })}
            name="status"
            options={[
              {
                label: intl.formatMessage({ id: 'systemManagement.generalProcedure.enable' }),
                value: true,
              },
              {
                label: intl.formatMessage({ id: 'systemManagement.generalProcedure.disable' }),
                value: false,
              },
            ]}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'systemManagement.requiredFields.status' }),
              },
            ]}
          />

          <ProFormTextArea
            colProps={{ md: 24 }}
            label={intl.formatMessage({
              id: 'systemManagement.deviceManagementMenu.remarksDescription',
            })}
            name="remark"
            fieldProps={{
              maxLength: 150,
            }}
          />
        </ModalForm>
      </Card>
    </>
  );
};

export default UpgradeManagement;
